//
//  WmcWatermarkSelectVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/4.
//

import RxRelay
import UIKit
import YPBedrock
import YPNetwork

// MARK: - 扩展WmcWatermarkSelectView + WmcVMProtocol

extension WmcWatermarkSelectView: WmcVMProtocol {
    typealias VMType = WmcWatermarkSelectVM
}

// MARK: - [WmcWatermarkSelectView]

class WmcWatermarkSelectView: WmcSelectView {
    // Lifecycle

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required convenience init() {
        self.init(frame: .zero)
    }

    // Internal

    lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout
            .YP.CreateGridLayout(scrollDirection: .horizontal,
                                 minimumLineSpacing: 0,
                                 minimumInteritemSpacing: 0,
                                 sectionInset: .zero)
        return layout
    }()

    lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView
            .YP.Create(layout: layout,
                       delegate: self,
                       dataSource: self,
                       registers: [
                           YPRegister(WmcWatermarkSelectCell.self),
                       ])
        collectionView.isPagingEnabled = true
        collectionView.alwaysBounceVertical = false // 内容填充不满也具有弹性效果
        return collectionView
    }()

    lazy var classifView: WmcWatermarkSelectClassifView = {
        let view = WmcWatermarkSelectClassifView()
        return view
    }()

    lazy var activityIndicator: UIActivityIndicatorView = {
        let activityIndicator = UIActivityIndicatorView()
        return activityIndicator
    }()

    /// 上一次的索引
    var beforeIndex: Int = 0
    /// 选中数组
    var selectArray: [[Bool]] = []
    /// 点击回调
    var didSelectWatermarkBlock: YPBlock.TwoParam<IndexPath, WmcWatermarkDetailModel>?
    /// 点击无水印回调
    var didSelectEmptyWatermarkBlock: YPBlock.OneParam<WmcWatermarkDetailModel>?
    /// 水印分享回调
    var shareWatermarkBlock: YPBlock.OneParam<WmcWatermarkDetailModel>?
    /// 编辑水印回调
    var editWatermarkBlock: YPBlock.OneParam<WmcWatermarkDetailModel>?
    /// 消失回调
    var dismissBlock: YPBlock.Empty?

    var selectWmModel: WmcWatermarkDetailModel?
    
    // 水印数据加载完成
    var watermarkListLoadCompletion: YPBlock.OneParam<[WmcWatermarkClassifyModel]>?

    override func makeUI() {
        super.makeUI()

        activityIndicator.startAnimating()
        addSubview(activityIndicator)
        activityIndicator.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.size.equalTo(50)
        }

        title = "我的水印"
        titleView.isShowLine = true
        titleView.leftBtn.setImage("disable".wmc_image, for: .normal)
        
        if let selectDelegate = YPWmcManager.shared.uiDelegate.selectWatermarkDelegate {
            if selectDelegate.watermarkSelectShowEmptyButton(.current) == true {
                titleView.leftBtn.isHidden = false
            } else {
                titleView.leftBtn.isHidden = true
            }
        }else{
            titleView.leftBtn.isHidden = false
        }
        
        titleView.rightBtn.setImage("close".wmc_image, for: .normal)

        addSubview(classifView)
        classifView.snp.makeConstraints { make in
            make.top.equalTo(titleView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(44)
        }

        addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(classifView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }

    override func bindViewAction() {
        // 无水印
        titleView.leftBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.setSelectArray(nil)
            weakSelf.didSelectEmptyWatermarkBlock?(.init())
        }

        // 切换分类
        classifView.classifyChangeSelectBlock = { [weak self] index, classif in
            guard let weakSelf = self else { return }
            // 页面切换
            let animation = CATransition()
            animation.duration = Wmc_animationDuration
            animation.type = .push
            if weakSelf.beforeIndex != index {
                if weakSelf.beforeIndex > index {
                    animation.subtype = .fromLeft
                } else {
                    animation.subtype = .fromRight
                }
                animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
                weakSelf.collectionView.scrollToItem(at: .init(row: index, section: 0),
                                                     at: .centeredHorizontally,
                                                     animated: false)
                weakSelf.collectionView.layer.add(animation, forKey: nil)
            }
            // 数据切换
            weakSelf.viewModel.switchClassify(classif)
        }
    }

    override func bindViewModel() {
        
        // 监听网络状态
        YPNetworkReachability.monitoring().subscribe(onNext: { [weak self] type in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.loadWatermarkList()
        }).disposed(by: rx.disposeBag)
        
        // 分类列表刷新
        viewModel.watermarkClassifyListRelay.skip(1).subscribe(onNext: { [weak self] list in
            guard let weakSelf = self else { return }
            // 设置分类
            weakSelf.classifView.snp.remakeConstraints { make in
                make.top.equalTo(weakSelf.titleView.snp.bottom)
                make.left.right.equalToSuperview()
                make.height.equalTo(44)
            }

            if list.count == 1 {
                weakSelf.classifView.isHidden = true
                weakSelf.collectionView.snp.remakeConstraints { make in
                    make.top.equalTo(weakSelf.titleView.snp.bottom)
                    make.left.right.bottom.equalToSuperview()
                }
            } else {
                weakSelf.classifView.isHidden = false
                weakSelf.collectionView.snp.remakeConstraints { make in
                    make.top.equalTo(weakSelf.classifView.snp.bottom)
                    make.left.right.bottom.equalToSuperview()
                }
            }
            weakSelf.classifView.setWatermarkList(list)
            weakSelf.watermarkListLoadCompletion?(list)
            weakSelf.activityIndicator.stopAnimating()
        }).disposed(by: rx.disposeBag)

        // 当前分类切换
        viewModel.currentWatermarkListRelay.skip(1).subscribe(onNext: { [weak self] wmList in
            guard let weakSelf = self else { return }
            if weakSelf.selectArray.isEmpty,
               let selectWmModel = weakSelf.selectWmModel
            {
                weakSelf.setSelectWatermark(selectWmModel)
            }
            weakSelf.collectionView.reloadData()
        }).disposed(by: rx.disposeBag)
    }

    /// 滑动到选中
    func scrollToSelect(_ indexPath: IndexPath, animated: Bool = true) {
        // 选中组
        let section = indexPath.section
        // 选中分类
        classifView.select(at: section)

        if beforeIndex != section {
            if collectionView.contentSize == .zero {
                yp.delayLast(0.1) { [weak self] in
                    guard let weakSelf = self else { return }
                    weakSelf.collectionView.selectItem(at: .init(row: section, section: 0),
                                                       animated: animated,
                                                       scrollPosition: .centeredHorizontally)
                }
            } else {
                collectionView.selectItem(at: .init(row: section, section: 0),
                                          animated: animated,
                                          scrollPosition: .centeredHorizontally)
            }
            beforeIndex = section
        }
        // 选中行
        let row = indexPath.row
        if let cell = collectionView.cellForItem(at: .init(row: section, section: 0)) as? WmcWatermarkSelectCell {
            cell.collectionView.scrollToItem(at: .init(row: row, section: 0),
                                             at: .centeredVertically,
                                             animated: animated)
        }
    }

    func setSelectWatermark(_ wmModel: WmcWatermarkDetailModel) {
        selectWmModel = wmModel
        let list = viewModel.watermarkClassifyListRelay.value
        selectArray.removeAll()
        var indexPath: IndexPath = .init(row: 0, section: 0)
        for (section, classify) in list.enumerated() {
            var sectionSelect: [Bool] = []
            if classify.classifyId == wmModel.classifyId {
                indexPath.section = section
                for (row, wm) in classify.watermarks.enumerated() {
                    if wm.wmId == wmModel.wmId {
                        indexPath.row = row
                        sectionSelect.append(true)
                    } else {
                        sectionSelect.append(false)
                    }
                }
            } else {
                for _ in classify.watermarks {
                    sectionSelect.append(false)
                }
            }
            selectArray.append(sectionSelect)
        }
        classifView.reloadData()
        classifView.layoutIfNeeded()
        collectionView.reloadData()
        scrollToSelect(indexPath, animated: false)
    }

    /// 设置选中数组
    func setSelectArray(_ select: IndexPath? = nil) {
        let list = viewModel.watermarkClassifyListRelay.value
        selectArray.removeAll()
        for (section, classify) in list.enumerated() {
            var sectionSelect: [Bool] = []
            for (row, _) in classify.watermarks.enumerated() {
                if select?.section == section,
                   select?.row == row
                {
                    sectionSelect.append(true)
                } else {
                    sectionSelect.append(false)
                }
            }
            selectArray.append(sectionSelect)
        }
        classifView.reloadData()
        classifView.layoutIfNeeded()
        collectionView.reloadData()
    }
}

// MARK: - UICollectionViewDelegate

extension WmcWatermarkSelectView: UICollectionViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let center = scrollView.frame.width / 2
        let index: Int = ((scrollView.contentOffset.x + center) / scrollView.frame.width).yp.int
        if beforeIndex != index {
            classifView.select(at: index)
            beforeIndex = index
        }
    }
}

// MARK: - UICollectionViewDelegateFlowLayout

extension WmcWatermarkSelectView: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return collectionView.frame.size
    }

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        if let cell = cell as? WmcWatermarkSelectCell {
            cell.willDisplay()
        }
    }
}

// MARK: - UICollectionViewDataSource

extension WmcWatermarkSelectView: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel.watermarkClassifyListRelay.value.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: WmcWatermarkSelectCell = collectionView.yp.dequeueReusableCell(for: indexPath)
        if let model = viewModel.watermarkClassifyListRelay.value.yp.object(at: indexPath.row),
           let rowSelectArray = selectArray.yp.object(at: indexPath.row)
        {
            cell.section = indexPath.row

            // 水印选中事件
            cell.didSelectWatermarkBlock = didSelectWatermarkBlock
            // 水印触发分享
            cell.shareBlock = shareWatermarkBlock
            // 水印触发编辑
            cell.editBlock = editWatermarkBlock
            // 消失回调
            cell.dismissBlock = dismissBlock
            cell.configModel(model, rowSelectArray: rowSelectArray)
        }
        return cell
    }
}
